import React, { useState, useEffect } from 'react';
import styles from './index.module.less';
import OfficialDocFooter, { NavType } from './components/footer';
import DocCreateTemplate from './components/create-template';
import Log from './components/log';
import MatterList from './components/matter-list';
import { useSelector } from 'react-redux';

const OfficialDoc: React.FC<any> = (props) => {
  const [selectedNav, setSelectedNav] = useState<NavType>();
  const [hasAddAuthArr, setHasAddAuthArr] = useState<string[]>([]);
  const menuType = props.match.params.menuType;

  const { userInfo, userMenu } = useSelector((state: any) => ({
    userInfo: state.common.userInfo?.user,
    userMenu: state.common.userMenu
  }));

  useEffect(() => {
    const hasAddAuthArr = checkOfficialAddAuth();
    setHasAddAuthArr(hasAddAuthArr);
    if (hasAddAuthArr.includes('official-add')) {
      setSelectedNav(NavType.CREATE);
      return
    }
    if (hasAddAuthArr.includes('official-record')) {
      setSelectedNav(NavType.LOG);
      return
    }
    if (hasAddAuthArr.includes('official-item')) {
      setSelectedNav(NavType.MATTER);
      return
    }
  }, [userMenu])

  const getContent = (): JSX.Element => {
    switch (selectedNav) {
      case NavType.CREATE:
        return <DocCreateTemplate />;
      case NavType.LOG:
        return <Log />;
      case NavType.MATTER:
        return <MatterList />;
      default:
        return <React.Fragment></React.Fragment>;
    }
  };

  const switchMenuType = (type: string = menuType) => {
    switch (type) {
      case '1': setSelectedNav(NavType.CREATE); break;
      case '2': setSelectedNav(NavType.LOG); break;
      case '3': setSelectedNav(NavType.MATTER); break;
      default: break;
    }
  };

  const checkOfficialAddAuth = () => {
    let hasAuthArr;
    userMenu.forEach((item: any) => {
      if (item.code === 'official-doc') { // code='official-add'对应公文菜单
        hasAuthArr = item?.children?.map((subItem: any) => subItem.code);
      }
    });
    return hasAuthArr;
  };

  useEffect(() => {
    switchMenuType();
  }, [menuType]);

  return (
    <div className={styles['wrap']}>
      {getContent()}
      <OfficialDocFooter selectedNav={selectedNav} hasAddAuthArr={hasAddAuthArr} />
    </div>
  );
};

export default OfficialDoc;